var api = require('../config/api.js');
var reg = require('../config/reg.js');

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//判断是否为空 空字符串 以及null undefined
function isEmpty(o){
  return trim(o).length === 0;
}
//判断是否不为空 
function isNotEmpty(o) {
  return !isEmpty(o);
}
//去除空格
function trim(o){
  if (o === null || o === undefined) {
    return "";
  }
  return o.trim();
}
/**
 * 验证邮箱格式
 */
function regexEmail(s) {
  return regex(reg.EMAIL,s);
}
/**
 * 验证正则表达式
 */
function regex(r,s) {
  return !r.test(s);
}
/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "POST", header = "application/x-www-form-urlencoded") {
  wx.showLoading({
    title: '加载中...',
  });
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: {
        'Content-Type': header,
        'accessToken': wx.getStorageSync('token')
      },
      success: function(res) {
        wx.hideLoading();
        if (res.statusCode == 200) {
          if (res.data.code == 401) {
            wx.navigateTo({
              url: '/pages/auth/btnAuth/index',
            })
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function(err) {
        reject(err)
      }
    })
  });
}

/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function(resolve, reject) {
    wx.checkSession({
      success: function() {
        resolve(true);
      },
      fail: function() {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function(resolve, reject) {
    wx.login({
      success: function(res) {
        if (res.code) {
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function(err) {
        reject(err);
      }
    });
  });
}


function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    image: '/static/images/icon_error.png'
  })
}

function showSuccessToast(msg) {
  wx.showToast({
    title: msg,
  })
}


function getCtx(selector) {
  const pages = getCurrentPages();
  const ctx = pages[pages.length - 1];

  const componentCtx = ctx.selectComponent(selector);

  if (!componentCtx) {
    console.error('无法找到对应的组件，请按文档说明使用组件');
    return null;
  }
  return componentCtx;
}

function Toast(options) {
  const {
    selector = '#toast'
  } = options;
  const ctx = getCtx(selector);

  ctx.handleShow(options);
}

Toast.hide = function(selector = '#toast') {
  const ctx = getCtx(selector);

  ctx.handleHide();
};

function Message(options) {
  const {
    selector = '#message'
  } = options;
  const ctx = getCtx(selector);

  ctx.handleShow(options);
}


module.exports = {
  regexEmail: regexEmail,
  regex:regex,
  isEmpty:isEmpty,
  isNotEmpty:isNotEmpty,
  trim:trim,
  $Toast: Toast,
  $Message: Message,
  formatTime,
  request,
  showErrorToast,
  showSuccessToast,
  checkSession,
  login,
}